package com.shenghua.controller;

import com.alibaba.fastjson.JSON;
import com.shenghua.dao.bean.UserBean;
import com.shenghua.dao.mapper.UserMapper;
import com.shenghua.dao.model.User;
import com.shenghua.dao.model.UserExample;
import com.shenghua.dao.page.Page;
import com.shenghua.service.UserService;
import com.shenghua.token.PassToken;
import com.shenghua.token.TokenUtils;
import com.shenghua.token.UserLoginToken;
import com.shenghua.utils.*;
import com.shenghua.utils.beans.Dto;
import com.shenghua.utils.beans.ErrorCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/12/23.
 */
@Controller
@RequestMapping(value="/user")
class UserController extends BaseController {
    Logger logger = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisUtils redisUtils;

    @RequestMapping(value = "/loginSys", method = RequestMethod.POST ,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String loginSys(User user, HttpServletRequest request,
                            HttpServletResponse response) {
        /*Dto<User> dto = new Dto<>();
        if(StringUtils.isBlank(user.getLinkman()) || StringUtils.isBlank(user.getPwd())){
            dto.setData(new User());
            dto.setErrorcode(   ErrorCode.AUTH_ILLEGAL_USERCODE.getKey());
            dto.setMsg(ErrorCode.AUTH_ILLEGAL_USERCODE.getValue());
            return JSON.toJSONString(dto);
        }
        // 获取登录的IP
        //user.setLastLoginIp(request.getRemoteAddr());
        user.setLastLoginIp(Iptool.getServerIp());
        dto = userService.login(user);
        if(ErrorCode.LOGIN_SUCCESS.getKey() == dto.getStatus()){
            HttpSession userSession = request.getSession();
            userSession.setAttribute("userSession",(User)dto.getData());
        }
        logger.info("[UserController] loginSys " + dto.getMsg());
        return JSON.toJSONString(dto);*/

        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getLinkman(),
                user.getPassword().toCharArray()
        );
        Dto<User> dto = new Dto<>();
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            dto.setData(new User());
            dto.setErrorcode(ErrorCode.AUTH_AUTHENTICATION_FAILED.getKey());
            dto.setMsg(ErrorCode.AUTH_AUTHENTICATION_FAILED.getValue());
            return JSON.toJSONString(dto);
        } catch (AuthorizationException e) {
            e.printStackTrace();
            dto.setData(new User());
            dto.setErrorcode(ErrorCode.AUTH_NO_LIMIT.getKey());
            dto.setMsg(ErrorCode.AUTH_NO_LIMIT.getValue());
            return JSON.toJSONString(dto);
        }
        UserBean userBean = (UserBean) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        User user1 = userBean.getUser();
        User user2 = new User();
        user2.setNickname(user1.getNickname());
        dto.ReturnSuccess(user2, ErrorCode.SUCCESS);
        return JSON.toJSONString(dto);
    }

    @RequestMapping(value = "/regUser", method = RequestMethod.POST ,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String registerUser(User user, HttpServletRequest request) {
        Dto<User> dto = userService.newRegister(user);
        return JSON.toJSONString(dto);
    }

    @RequestMapping(value = "/checkLinkman", method = RequestMethod.POST ,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String checkLinkman(String linkman, HttpServletRequest request) {
        Dto<String> dto = new Dto<>();
        dto = userService.checkLinkman(linkman);
        return JSON.toJSONString(dto);
    }

    @RequestMapping(value = "/exitSys", method = RequestMethod.POST ,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String exitSys(HttpServletRequest request) {
        Dto<String> dto = new Dto<>();
        HttpSession userSession = request.getSession();
        User user = (User) userSession.getAttribute("userSession");
        String linkman = "";
        if(null != user) {
            linkman = user.getNickname();
        }
        if(redisUtils.exist(user.getLinkman())) {
            logger.debug("[UserServiceImpl] exitSys 用户已经登录，可以释放锁！");
            redisUtils.unlock(user.getLinkman());
        }
        userSession.setAttribute("userSession","");
        logger.info("[UserController] exitSys "+linkman+"成功退出系统");
        dto.ReturnSuccess("",ErrorCode.USER_EXIT_SYSTEM);
        return JSON.toJSONString(dto);
    }

    @RequestMapping(value = "/userManager/normal")
    public String userManagerPage_Normal() {
        return "pc/user/userManager";
    }

    //编辑用户页面
    @RequestMapping(value = "/editUser/normal/{id}", method = RequestMethod.GET ,produces = "application/json;charset=utf-8")
    public String editUserPage_Normal(@PathVariable("id") String id, Model model) {
        User user = userMapper.selectByPrimaryKey(Integer.parseInt(id));
        if(null == user) {
            logger.error("[UserController] editUserPage_Normal 未找到指定用户");
            return "page500";
        }
        model.addAttribute("user",user);
        return "pc/user/editUser";
    }

    //编辑用户信息
    @RequestMapping(value = "/editCurrentUser/normal",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String editCurrentUser_Normal(User user, HttpServletRequest request) {
        logger.info("[UserController] editCurrentUser_Normal user:{}",JSON.toJSONString(user));
        Dto<User> dto = new Dto<>();
        User u = (User)request.getSession().getAttribute("userSession");
        if(null == u) {
            logger.debug("[UserController] editCurrentUser_Normal 用户未登录");
            dto.ReturnFail(new User(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        user.setUpdated(new Date());
        dto = userService.editCurrentUser(user);
        return JSON.toJSONString(dto);
    }


    //查询用户信息
    @RequestMapping(value = "/selectUserByPage",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String selectMouldByPage(@RequestParam Map<String,Object> params) {
        Page page = getRequestPageInfo(params);
        Dto<Map<String,Object>> dto = userService.queryUserByPage(params, page);
        return JSON.toJSONString(dto);
    }

    @RequestMapping(value = "/owlClock/normal")
    public String owlClock_Normal() {
        return "page/owlClock";
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    @ResponseBody
    public String getMessage(){
        return "你已通过验证";
    }

    @PassToken
    @PostMapping("/getToken")
    @ResponseBody
    public String getToken(@RequestParam("username") String username, @RequestParam("password") String password){
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andLinkmanEqualTo(username);
        criteria.andPwdEqualTo(MD5Util.getMD5(password));
        List<User> userList = userMapper.selectByExample(example);
        System.out.println(JSON.toJSONString(userList));
        String token = "";
        if(ListUtils.isNotEmpty(userList)) {
            User user  = userList.get(0);
            token = TokenUtils.getToken(user);
        }
        System.out.println("token:" + token);
        return token;
    }
}
